import Vue from 'vue'
// 引入im
import TIM from 'tim-wx-sdk';
import COS from "cos-wx-sdk-v5";

export default{
	// 对接IM
	getIM(){
		// 登陆
		let im = Vue.prototype.$tim.login({
			userID: uni.getStorageSync('im_account'),
			userSig: uni.getStorageSync('im_sig')
		});
		im.then((e) => { //登陆成功
			console.log('登录成功')
			setTimeout(()=>{
				let promise = Vue.prototype.$tim.getConversationList();
				promise.then((imResponse)=> {
				  const conversationList = imResponse.data.conversationList; // 会话列表，用该列表覆盖原有的会话列表
				  console.log(conversationList)
				  let arr = []
				  for (var i = 0; i < conversationList.length; i++) {
					  if(conversationList[i].type == "C2C"){
						 arr.push(conversationList[i]) 
					  }
				  }
				  let num = 0
				  for (var i = 0; i < arr.length; i++) {
					num = parseInt(arr[i].unreadCount) + num
				  }
				  uni.setStorageSync('msgNum',num)
				  if(num !== 0){
					  uni.setTabBarBadge({
					  	index:3,
					  	text:uni.getStorageSync('msgNum').toString()
					  })
				  }else{
					  uni.removeTabBarBadge({
					  	index:3
					  })
				  }

				}).catch((imError)=> {
				  console.warn('getConversationList error:', imError); // 获取会话列表失败的相关信息
				});
			},1000)
		})
		im.catch((err)=>{
			console.log('登陆失败')
		})
	},
	onMessage(){
		let onMessageReceived = (event)=> {
			for (var i = 0; i < event.data.length; i++) {
				if(event.data[i].conversationType == 'C2C'){
					let promise = Vue.prototype.$tim.getConversationList();
					promise.then((imResponse)=> {
					  const conversationList = imResponse.data.conversationList; // 会话列表，用该列表覆盖原有的会话列表
					  console.log(conversationList)
					  let arr = []
					  for (var i = 0; i < conversationList.length; i++) {
						  if(conversationList[i].type == "C2C"){
							 arr.push(conversationList[i]) 
						  }
					  }
					  let num = 0
					  for (var i = 0; i < arr.length; i++) {
						num = parseInt(arr[i].unreadCount) + num
					  }
					  uni.setStorageSync('msgNum',num)
					  if(num !== 0){
						  uni.setTabBarBadge({
						  	index:3,
						  	text:uni.getStorageSync('msgNum').toString()
						  })
					  }else{
						  uni.removeTabBarBadge({
						  	index:3
						  })
					  }

					}).catch((imError)=> {
					  console.warn('getConversationList error:', imError); // 获取会话列表失败的相关信息
					});
				}
			}

		};
		Vue.prototype.$tim.on(TIM.EVENT.MESSAGE_RECEIVED, onMessageReceived);
	},
	onTab(){
		let num = uni.getStorageSync('msgNum')
		if(num == '' || num == 0){
			uni.removeTabBarBadge({
				index:3
			})
		}else{
			uni.setTabBarBadge({
				index:3,
				text:uni.getStorageSync('msgNum').toString()
			})
		}
	}
}
